import React, { useEffect, useState, useLayoutEffect, useRef } from "react";
import { env, config, api, utils, apis } from "mdye";
import styled from "styled-components";
import icon from "./icon.svg";

const Con = styled.div`
  height: 100vh;
  display: flex;
  flex-direction: row;
  background: #fff;
  .mt10 {
    margin-top: 10px;
  }
  > div {
    height: 100%;
    box-sizing: border-box;
  }
  .brand {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .logo {
      position: relative;
      img {
        position: relative;
        width: 200px;
        z-index: 1;
      }
    }
    .hello {
      margin-top: 20px;
      font-family: Verdana;
      font-weight: bold;
      font-size: 50px;
      color: #444;
    }
    .edit {
      margin-top: 10px;
      font-size: 16px;
      color: #888;
    }
    .records-count {
      margin-top: 10px;
      font-size: 16px;
      color: #666;
    }
  }
  .playground {
    flex: 1;
    max-width: 600px;
    overflow-x: hidden;
    overflow-y: auto;
    .con {
      padding: 20px 40px;
    }
    .block {
      border-radius: 10px;
      overflow: hidden;
      border: 1px solid rgba(188, 209, 228, 0.44);
      margin-bottom: 12px;
      .header {
        color: #666;
        padding-left: 14px;
        font-size: 13px;
        height: 32px;
        line-height: 32px;
        border-bottom: 1px solid rgba(188, 209, 228, 0.44);
      }
      .content {
        font-size: 13px;
        padding: 10px 18px;
        white-space: pre;
        color: #50a14f;
        line-height: 1.3em;
      }
    }
    .operate-title {
      margin: -4px 0 4px;
      font-weight: bold;
      color: #555;
      .prefix {
        color: #00a1ff;
        margin-right: 5px;
      }
    }
    .button {
      margin: 6px 6px 0 0;
      font-size: 13px;
      display: inline-block;
      border: 1px solid #bcd1e4;
      border-radius: 4px;
      height: 32px;
      line-height: 30px;
      padding: 0 16px;
      color: #5d6f7e;
      cursor: pointer;
      user-select: none;
      &:hover {
        background: #fafafa;
      }
    }
    .log {
      font-size: 14px;
      max-height: 200px;
      overflow-y: auto;
      .base {
        color: #0451a5;
      }
      .log-item {
        white-space: break-spaces;
        color: #555;
        line-height: 1.3em;
        .time {
          margin-right: 5px;
          color: #307c58;
        }
      }
    }
  }
  @media (max-width: 1000px) {
    flex-direction: column;
    overflow-y: auto;
    height: auto;
    .brand {
      flex: none;
      padding: 100px 0;
    }
    .playground {
      flex: none;
      max-width: none;
    }
  }
`;

function JSONPre(props) {
  const {
    normalColor = "#383a42",
    attrColor = "#986801",
    valueColor = "#50a14f",
    json = {},
  } = props;
  const length = Object.keys(json).length;
  return (
    <div
      style={{
        whiteSpace: "pre",
        color: normalColor,
      }}
    >
      <div>{`{`}</div>
      {Object.keys(json).map((key, i) => (
        <div style={{ paddingLeft: 14 }} key={i}>
          <span style={{ color: attrColor }}>"{key}"</span>:
          <span style={{ color: valueColor, marginLeft: 6 }}>
            {typeof json[key] === "string"
              ? `"${json[key]}"`
              : JSON.stringify(json[key]) || `""`}
          </span>
          {i !== length - 1 && <span>,</span>}
        </div>
      ))}
      <div>{`}`}</div>
    </div>
  );
}

export default function () {
  const { appId, worksheetId, viewId } = config;
  const { getFilterRows, getFilterRowsTotalNum } = api;
  const logRef = useRef();
  const [count, setCount] = useState();
  const [logs, setLogs] = useState([
    { time: new Date(), content: "hello world!" },
  ]);
  function addLog(content) {
    setLogs((old) => [...old, { time: new Date(), content }]);
  }
  async function loadRecordsCount() {
    addLog("正在获取记录数量...");
    const res = await getFilterRowsTotalNum({ worksheetId, viewId });
    addLog(`当前视图共${res}条记录`);
    setCount(res);
  }
  useEffect(() => {
    loadRecordsCount();
    apis.instanceVersion.getTodoList({}).then((res) => {
      console.log(res);
    });
  }, []);
  useLayoutEffect(() => {
    if (logRef.current) {
      logRef.current.scrollTop = 10000;
    }
  });
  return (
    <Con>
      <div className="brand flex-1">
        <div className="logo">
          <img src={icon} />
        </div>
        <div className="hello">Hello React-89123!</div>
        <div className="edit">编辑项目下的 src/App.js 开始开发吧</div>
        <div className="records-count">
          当888前视图共 <b>{typeof count !== "undefined" ? count : "?"}</b> 条记录
        </div>
      </div>
      <div className="playground flex-1">
        <div className="con">
          <div className="block">
            <div className="header">env 映射信息</div>
            <div className="content">
              {Object.keys(env).length === 0 ? (
                "没有配置"
              ) : (
                <JSONPre json={env} />
              )}
            </div>
          </div>
          <div className="block">
            <div className="header">config 视图信息</div>
            <div className="content">
              <JSONPre
                json={{
                  appId,
                  worksheetId,
                  viewId,
                }}
              />
            </div>
          </div>
          <div className="operate-title">
            <span className="prefix">❯</span>组件调用
          </div>
          <div>
            <div
              className="button"
              onClick={() => {
                addLog("打开新建记录弹窗");
                utils
                  .openNewRecord({
                    worksheetId,
                  })
                  .then((row) => {
                    addLog("创建成功，新纪录 id 是" + row.rowid);
                  });
              }}
            >
              新建记录
            </div>
            <div
              className="button"
              onClick={() => {
                utils
                  .selectRecord({
                    relateSheetId: worksheetId,
                  })
                  .then((records) => {
                    utils
                      .openRecordInfo({
                        appId,
                        worksheetId,
                        recordId: records[0].rowid,
                      })
                      .then((updatedRow) => {
                        console.log({ updatedRow });
                      });
                  });
              }}
            >
              打开记录
            </div>
            <div
              className="button"
              onClick={() => {
                utils
                  .selectRecord({
                    relateSheetId: worksheetId,
                    multiple: true,
                  })
                  .then((records) => {
                    addLog("已选择记录 " + records.map((r) => r.rowid));
                  });
              }}
            >
              选择记录
            </div>
          </div>
          <div>
            <div
              className="button"
              onClick={async () => {
                addLog("打开选择人员弹窗");
                const users = await utils.selectUsers();
                console.log(users);
                addLog("已选择人员 " + users.map((u) => u.fullname));
              }}
            >
              选择人员
            </div>
            <div
              className="button"
              onClick={() => {
                addLog("打开选择部门弹窗");
                utils.selectDepartments().then((departments) => {
                  addLog(
                    "已选择部门 " + departments.map((d) => d.departmentName)
                  );
                });
              }}
            >
              选择部门
            </div>
            <div
              className="button"
              onClick={() => {
                addLog("打开选择组织角色弹窗");
                utils.selectOrgRole().then((orgs) => {
                  addLog("已选择组织角色 " + orgs.map((o) => o.organizeName));
                });
              }}
            >
              选择组织角色
            </div>
            <div
              className="button"
              onClick={() => {
                addLog("打开选择选择地图定位弹窗");
                utils
                  .selectLocation({
                    closeAfterSelect: true,
                  })
                  .then((location) => {
                    console.log(location);
                    addLog(
                      "已选择地图定位 " + (location.name || location.address)
                    );
                  });
              }}
            >
              选择地图定位
            </div>
          </div>
          <div className="block mt10 log" ref={logRef}>
            <div className="content">
              <div className="base">~/mdye</div>
              {logs.map((log, i) => (
                <div className="log-item" key={i}>
                  <span className="time">
                    [
                    {[
                      log.time.getHours(),
                      log.time.getMinutes(),
                      log.time.getSeconds(),
                    ]
                      .map((num) => String(num).padStart(2, 0))
                      .join(":")}
                    ]
                  </span>
                  {log.content}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Con>
  );
}
